package com.qianya.system.face.web.patient.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.jdbc.result.UpdatableResultSet;
import com.qianya.model.common.JWTUtil;
import com.qianya.model.pojo.patient.qo.PatientHisPrescriptionQO;
import com.qianya.model.pojo.patient.vo.MonthVo;
import com.qianya.model.pojo.patient.vo.PatientHisPrescriptionVO;
import com.qianya.system.face.config.RedisUtil;
import com.qianya.system.face.web.patient.model.PatientBoxRelevance;
import com.qianya.system.face.web.patient.model.PatientFileInfo;
import com.qianya.system.face.web.patient.service.IPatientBoxRelevanceService;
import com.qianya.system.face.web.patient.service.IPatientFileInfoService;
import com.qianya.system.face.web.patient.service.IPatientHisPrescriptionService;
import com.qianya.system.face.web.patient.model.PatientHisPrescription;
import com.qianya.system.face.web.patient.mapper.PatientHisPrescriptionMapper;
import com.qianya.util.DateUtils;
import com.qianya.util.RandUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qianya.model.common.CommonResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qianya.model.common.ResultCode;
import org.springframework.web.jsf.el.WebApplicationContextFacesELResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
* <p>
*  服药日志表服务实现类
* </p>
*
* @author lhl
* @since 2020-07-07
*/
@Service
public class PatientHisPrescriptionServiceImpl extends ServiceImpl<PatientHisPrescriptionMapper, PatientHisPrescription> implements IPatientHisPrescriptionService {
        @Autowired
        private IPatientBoxRelevanceService boxRelevanceService;
        @Autowired
        private IPatientFileInfoService patientFileInfoService;
        @Resource
        private PatientHisPrescriptionMapper hisPrescriptionMapper;
        /**
        *查找 服药日志表
        * @author lhl
        * @since 2020-07-07
        */
        @Override
        public CommonResult find(PatientHisPrescriptionQO patientHisPrescription) {
            QueryWrapper<PatientHisPrescription> queryWrapper=new QueryWrapper<PatientHisPrescription>();
            if (null!=patientHisPrescription.getDrugStatus()){
                queryWrapper.eq("drug_status",patientHisPrescription.getDrugStatus());
            }
            queryWrapper.eq("file_id",patientHisPrescription.getFileId());
            IPage<PatientHisPrescription> iPage = page(new Page<PatientHisPrescription>(patientHisPrescription.getPageNo(),patientHisPrescription.getPageSize()),queryWrapper);
            return CommonResult.success(iPage);
        }
        /**
        * 新增 服药日志表
        * @author lhl
        * @since 2020-07-07
        */
        @Override
        public CommonResult create(PatientHisPrescription patientHisPrescription,HttpServletRequest request) {
            boolean b = save(patientHisPrescription);
            if (b){
                return CommonResult.success();
            }
            return CommonResult.error(ResultCode.ERROR,"操作失败");
        }
    /**
     * @desc 查询医嘱
     * @author lhl
     * @date 2020-07-20 16:02
     * @return
    */
    @Override
    public CommonResult view(String fileId) {
        PatientFileInfo pfi=patientFileInfoService.getById(fileId);
        if (pfi==null){
            return CommonResult.error(ResultCode.PATIENT_NOT_FOUND,"患者档案编号不存在");
        }
        List<String> list= DateUtils.theThreeTimeQuantum();
        Calendar calendar=Calendar.getInstance();
        int hours=calendar.get(calendar.HOUR_OF_DAY);
        QueryWrapper<PatientBoxRelevance> pbrWrapper=new QueryWrapper<PatientBoxRelevance>();
        pbrWrapper.eq("br_state",1).eq("file_identity_card",pfi.getFilePatientIdNum());
        if (hours>=7 && hours<12){
            pbrWrapper.gt("create_time",list.get(0)).lt("create_time",list.get(1));
        }else if (hours>=12 && hours<18){
            pbrWrapper.gt("create_time",list.get(1)).lt("create_time",list.get(2));
        }else if(hours>=18){
            pbrWrapper.gt("create_time",list.get(2)).lt("create_time",list.get(3));
        }
        PatientBoxRelevance pbrs=boxRelevanceService.getOne(pbrWrapper);
        if (pbrs==null){
            return CommonResult.error(ResultCode.Doctor_ORDER_NOT_FOUND,"没有查询到该患者医嘱");
        }
        List<PatientHisPrescription> phpList=list(new QueryWrapper<PatientHisPrescription>().eq("br_id",pbrs.getBrId()).eq("drug_status",1));
        if (phpList==null){
            return CommonResult.error(ResultCode.Doctor_ORDER_NOT_FOUND,"没有查询到该患者医嘱");
        }
        return  CommonResult.success(phpList);
        //return CommonResult.success(list(new QueryWrapper<PatientHisPrescription>().eq("file_id",pfi.getFileId()).gt("drug_time",list.get(0)).le("drug_time",list.get(1))));
    }
    /**
     * @desc 每个月服药统计
     * @author lhl
     * @date 2020-07-30 17:13
     * @return
    */
    @Override
    public List<MonthVo> eatStatistics() {
        Calendar end = Calendar.getInstance();
        end.setTime(new Date());
        end.add(Calendar.DAY_OF_MONTH, 1);
        Calendar begin = Calendar.getInstance();
        BeanUtils.copyProperties(end,begin);
        begin.add(Calendar.YEAR, -1);

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-01");

        List<MonthVo> patientStatic=hisPrescriptionMapper.eatStatistics(sdf.format(begin.getTime()),sdf.format(end.getTime()));
        return DateUtils.listChangeMapReturn(patientStatic,sdf.format(begin.getTime()), sdf.format(end.getTime()));

    }

    /**
     * @desc 当天发药记录
     * @author lhl
     * @date 2020-07-21 17:12
     * @return
    */
    @Override
    public CommonResult today() {
        List<String> list= DateUtils.theSameDay();
        IPage iPage = boxRelevanceService.page(new Page<PatientBoxRelevance>
                (1,3,true)
                ,new QueryWrapper<PatientBoxRelevance>().gt("update_time",list.get(0)).lt("update_time",list.get(1)).eq("br_state",0).orderByDesc("update_time"));
        if (CollUtil.isEmpty(iPage.getRecords())){
            iPage.setRecords(new ArrayList<PatientFileInfo>());
        }else {
            List<PatientBoxRelevance> listPb=iPage.getRecords();
            List<PatientFileInfo> listPf=new ArrayList<>();
            PatientFileInfo pfi=null;
            for (int i = 0; i <listPb.size() ; i++) {
                pfi=patientFileInfoService.getOne(
                        new QueryWrapper<PatientFileInfo>().eq("file_patient_id_num",listPb.get(i).getFileIdentityCard()));
                if (pfi!=null){
                    pfi.setFileUpdateTime(listPb.get(i).getUpdateTime());
                    listPf.add(pfi);
                }

            }
            iPage.setRecords(listPf);
        }
        return CommonResult.success(iPage);
    }

    /**
     * @desc 服药统计
     * @author lhl
     * @date 2020-07-24 11:47
     * @return
    */
    @Override
    public int eatMedicCount(int type) {
        QueryWrapper<PatientHisPrescription> queryWrapper=new QueryWrapper<PatientHisPrescription>();
        queryWrapper.eq("drug_status",0);
        List<String> timeList=DateUtils.theSameDay();
        if (type==1){
            queryWrapper.gt("drug_time",timeList.get(0));
        }
        return count(queryWrapper);
    }
    /**
     * @desc  根据时间和身份证号查询当天服药详情
     * @author lhl
     * @date 2020-08-07 15:26
     * @return
    */
    @Override
    public CommonResult patientOneDayMedicineDateils(String fileIdentityCard,String time) {
        Date date=DateUtils.parse(time,"yyyy-MM-dd");
        List<String> list=DateUtils.todayPutMedicTime(date);
        return CommonResult.success(hisPrescriptionMapper.patientOneDayMedicineDateils(fileIdentityCard,list.get(0),list.get(1)));
    }

    /**
        * 修改 服药日志表
        * @author lhl
        * @since 2020-07-07
        */
        @Override
        public CommonResult renewal(PatientHisPrescription patientHisPrescription,HttpServletRequest request) {
            boolean b = updateById(patientHisPrescription);
            if (b){
                return CommonResult.success();
            }
            return CommonResult.error(ResultCode.ERROR,"操作失败");
        }
    /**
     *
     * @author lhl
     * @since 2020-07-07
     */
    @Override
    public CommonResult dispensing(String hpId, HttpServletRequest request) {
        PatientHisPrescription php=getById(hpId);
        if (php==null){
            return CommonResult.error(ResultCode.ERROR,"未查询到该医嘱编号");
        }
        php.setDrugStatus(0);

         php.setUpdateId(JWTUtil.getUserId(request.getHeader("token")));
        php.setDrugTime(new Date());
        if (updateById(php)){
                /*修改关联表*/
                PatientBoxRelevance pbr=new PatientBoxRelevance();
                pbr.setBrId(php.getBrId());
                pbr.setBrState(0);
                pbr.setCreateTime(new Date());
                pbr.setUpdateTime(new Date());
                pbr.setUpdateId(JWTUtil.getUsername(request.getHeader("token")));
                boxRelevanceService.updateById(pbr);


              /*修改患者信息表*/
            PatientFileInfo patientFileInfo = new PatientFileInfo();
            patientFileInfo.setFileId(php.getFileId());
            patientFileInfo.setFileDoctorAdvice(php.getDrugUsage());
            boolean b = patientFileInfoService.updateById(patientFileInfo);
            if (b==false) {
                return CommonResult.error(ResultCode.ERROR,"医嘱无效");
            }


            return CommonResult.success();
        }
        return CommonResult.error(ResultCode.ERROR,"系统错误");
    }


}
